/**
 * 
 */
package com.yy.young.base.exception;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yy.young.base.util.GlobalConstants;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;


/**
 * @author rookie
 *
 */
public class ExceptionHandler implements HandlerExceptionResolver {

	private Logger logger = Logger.getLogger(ExceptionHandler.class);

	@Override
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		String url = request.getRequestURL().toString();
		logger.error("Exception Occured:: URL=" + url, ex);
		if (!(request.getHeader("accept")!=null && request.getHeader("accept").indexOf("application/json") > -1 || 
		        request.getHeader("X-Requested-With")!=null && request.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1)) {//如果不是异步请求
			Map<String, Object> model = new HashMap<String, Object>();
			model.put("url", url);
			model.put("ex", ex);
			/*
			 * //不同错误可以转向不同页面 if(ex instanceof BusinessException) { return new
			 * ModelAndView("error-business", model); }else if(ex instanceof
			 * ParameterException) { return new ModelAndView("error-parameter",
			 * model); } else { return new ModelAndView("error", model); }
			 */
			
			return new ModelAndView("redirect:" + GlobalConstants.REDIRECT.EXCEPTION, model);
		}else{
			PrintWriter pw = null;
            try {
            	response.setCharacterEncoding("UTF-8");
            	pw = response.getWriter();
            	String josn = ex.getMessage();
            	JSONObject o = new JSONObject();
            	if(ex instanceof YoungBaseException){
            		o.put("info", ((YoungBaseException)ex).getErrorInfo());
                	o.put("code",((YoungBaseException)ex).getErrorCode());
    			}else{
    				o.put("info", "系统异常:"+josn);
                	o.put("code","-999");
    			}
            	pw.write(o.toString());  
            } catch (IOException e) {  
                e.printStackTrace();  
            }finally{
            	try{
            		if(pw!=null)
            			pw.close();
            	}catch (Exception e) {
            		logger.error("错误拦截器关闭PrintWriter异常",e);
				}
            }
            return new ModelAndView();
		}
	}

}
